package com.rapida.example.plugin;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.rapida.framwork.IBOutlet;
import com.rapida.framwork.IVOutlet;
import com.rapida.framwork.UIViewController;
import com.rapida.plugin.PluginInfo;

/**
 * Created by mm on 2015/1/19.
 */
@IVOutlet(id = R.layout.theme)
public class MainUIController extends UIViewController implements AdapterView.OnItemClickListener {
	@IBOutlet(id=R.id.list)
	private ListView mPluginList;
	private PluginAdapter mAdapter;
	private ExampleThemeActivity mActivity;

	public MainUIController(ExampleThemeActivity activity) {
		mActivity = activity;
	}

	@Override
	public void viewDidLoad() {
		mAdapter = new PluginAdapter(mActivity);
        mPluginList.setAdapter(mAdapter);
        mPluginList.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
	}

	class PluginAdapter extends BaseAdapter {
		private Context baseContext;
		private LayoutInflater inflater;
		public PluginAdapter(Context context) {
			baseContext = context;
			inflater = LayoutInflater.from(baseContext);
		}

		@Override
		public int getCount() {
			return mActivity.getPlugins().size();
		}

		@Override
		public Object getItem(int position) {
			return mActivity.getPlugins().get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = inflater.inflate(android.R.layout.activity_list_item, null, false);
				holder = new ViewHolder();
				holder.icon = (ImageView) convertView.findViewById(android.R.id.icon);
				holder.name = (TextView) convertView.findViewById(android.R.id.text1);
				convertView.setTag(holder);
			} else{
				holder = (ViewHolder) convertView.getTag();
			}
			fillView(position, holder);
			return convertView;
		}

		private void fillView(int position, ViewHolder holder) {
			PluginInfo pluginInfo = mActivity.getPlugins().get(position);
			holder.name.setText(pluginInfo.pluginName);
			holder.icon.setImageDrawable(pluginInfo.pluginIcon);
		}
	}

	static class ViewHolder {
		TextView name;
		ImageView icon;
	}

}
